// -----------------------------------------------------------------------
//  <copyright file="DeleteUserCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/10 14:49:19</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Identity.Domain.Entities;
using DaprPlus.Identity.Domain.IntegrationEvents;

using Microsoft.Extensions.DependencyInjection;

namespace DaprPlus.Identity.Application.Identity.Users.Commands;

[AuthConfig(typeof(User), ResourceAccessType.RoleLimit, "Delete")]
public class DeleteUserCommand(long[] ids) : IRequest<ApiResult>, ICommand
{
    public long[] Ids { get; set; } = ids;
}

public class DeleteUserCommandHandler(IServiceProvider provider)
    : IRequestHandler<DeleteUserCommand, ApiResult>
{
    public async Task<ApiResult> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
    {
        var repository = provider.GetRequiredService<IRepository<User>>();
        var spec = new UserByIdsSpec<User>(request.Ids);
        var count = await repository.DeleteBatchAsync(spec, cancellationToken);
        if (count > 0)
        {
            var uow = provider.GetUnitOfWork();
            uow.AddIntegrationEvent(new UserDeletedIntegrationEvent(request.Ids));
        }

        return ApiResult.SuccessOrNoChanged(count > 0, $"{count} 个用户信息删除成功。");
    }
}

